// pages/user/user.js
// let network = require("../../utils/network/network.js")
// let api = require("../../utils/network/config.js").api;
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    userSession: {},
    isLogin: false,
    defaultUrl: 'https://rs.flik1337.cn/',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try {
      let userInfo = wx.getStorageSync('userInfo')
      let userSession = wx.getStorageSync('userSession')
      if (userInfo) {
        this.setData({
          userInfo: userInfo,
          userSession: userSession,
          isLogin: true
        })

      } else {
        this.setData({
          isLogin: false
        })
      }
    } catch (e) {

    }
  },
  login() {
    let _this = this
    wx.login({
      success(res) {
        console.log(res)
        if (res.code) {
          //发起网络请求
          network.fetch({
              url: api.user_login,
              data: {
                code: res.code
              },
              inBody: false,
              method: 'GET',
            })
            .then(res => {
              console.log(res)
              _this.setData({
                userInfo: res.data
              })
              wx.setStorageSync('userInfo', res.data)
              getApp().globalData.userInfo = res.data;

              _this.updateUserInfo();
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  getUserProfile() {
    let _this = this

    wx.getUserProfile({
      desc: '用于展示用户昵称、头像', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        _this.login();
        this.setData({
          userSession: res.userInfo,
          isLogin: true
        })
        getApp().globalData.userSession = res.userInfo;
        getApp().globalData.isLogin = true;

        wx.setStorageSync('userSession', res.userInfo)

      },
      fail: (e) => {
        console.log(e)
      }
    })
  },
  updateUserInfo() {
    let userSession = this.data.userSession;
    console.log(this.data.userInfo)
    let data = {
      nickName: userSession.nickName,
      uid: this.data.userInfo.uid,
      avatarUrl: userSession.avatarUrl,
    }
    network.fetch({
        url: api.user_update,
        data: data,
        inBody: true,
        method: 'POST',
      })
      .then(res => {
        console.log(res)
      })
  },
  toLogin() {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  toOrderList() {
    wx.navigateTo({
      url: '../userOrderList/userOrderList',
    })
  },
  logout() {
    wx.clearStorageSync('userInfo')
    wx.reLaunch({
      url: '/pages/login/login',
    })
  },
  toUserLotteryList(e) {
    wx.navigateTo({
      url: '../userLotteryList/userLotteryList?type=' +
        e.currentTarget.dataset.type +
        '&isCreate=' + e.currentTarget.dataset.isCreate,
    })
  }



})